<?php

namespace log_center;

use think\Db;
use think\facade\Config;

class Log
{
    protected $config = [];

    protected $component;

    protected $module;

    protected $routeKey;

    protected $routeValue = [];

    protected $writeLog = false;

    public static function init($component)
    {
        $logInstance = new self();
        $logInstance->component = $component;
        $logInstance->config = Config::get('log_modules');
        return $logInstance;
    }


    public function route($route)
    {
        foreach ($this->config as $moduleItem) {
            if (isset($moduleItem['routes'][$route])) {
                $this->routeValue = $moduleItem['routes'][$route];
                $this->module = $moduleItem['name'];
                $this->routeKey = $route;
                $this->writeLog = true;
                break;
            }
        }
        return $this;
    }


    public function write($params)
    {
        if (!$this->writeLog) {
            return;
        }

        $insetItem = [
            'log_time' => time(),
            'ip' => getClientIP(),
            'user_id' => $params['user_id'] ?? 0,
            'component' => $this->component,
            'module' => $this->module,
            'behavior' => $this->routeValue['name'] ?? '',
            'route' => $this->routeKey,
        ];

        $logServiceClass = '\\app\\' . $this->component . '\\service\\LogService';
        $method = $this->routeValue['method'];


        try {
            $operate = $logServiceClass::$method($params);
        } catch (\Exception $e) {
            $operate = '没有对应方法';
        } catch (\Throwable $t) {
            $operate = '没有对应方法';
        }


        $insetItem['operation'] = $operate;
        Db::table('tm_log_center')->insertGetId($insetItem);
    }
}